//  外观模式    Facade模式不仅简化了整个组件系统的接口，
//同时对于组件内部与外部客户程序来说，
//从某种程度上也达到了一种“解耦”的效果——内部子系统的任何变化不会影响到Façade接口的变化。
class Request {
  ajax() {
    return new Promise((resolve, reject) => {
      console.log("进行ajax请求")
      reject("网络错误")
    });
  }
}

class Logger {
  log(text){
    console.log(text)
  }
}

class Timer {
  constructor() {
    this.action = null;
    this.invokeTimes = 0;
    this.times = 0;
    this.timeout = 1000;
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve
      this.reject = reject
    })
    this.logger = new Logger();
  }

  retry(action, times = 3, timeout=1000) {
    this.action = action;
    this.times = times;
    this.timeout = timeout;
    this.innerInvoke();
    return this.promise;
  }

  innerInvoke() {
    this.action().then(() => {
      this.resolve()
    }, (err) => {
      console.log(err)
      this.invokeTimes++;
      this.logger.log("重试第" + this.invokeTimes + "次")
      if(this.invokeTimes > this.times) {
        this.reject()
        return;
      }
      setTimeout(() => {
        this.innerInvoke()
      }, this.timeout)
    })
  }
}

class RequestFacade {
  ajax() {
    var request = new Request();
    var logger = new Logger();
    // let comResolve=null;
    // let conRejec=null
    // let complete=new Promise((re,pr) => {
    //   comResolve=re
    //   conRejec=pr
    // })
   new Timer().retry(request.ajax).then(()=>{
      logger.log("调用成功")
      // comResolve('成功')
    }, ()=>{
      logger.log("调用失败")
      // conRejec('失败')
    })
    // return complete
  }

}
const requestFacade=new RequestFacade()
requestFacade.ajax()
// .then((data) => {
//   console.log(data)
// },(err) => {
//   console.log(err)
// })